<template>
  <div class="trading-chart-demo">
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>游资交易图表</span>
          <div class="header-actions">
            <el-button link @click="refreshData">
              <el-icon>
                <Refresh />
              </el-icon>
              刷新数据
            </el-button>
            <el-button link @click="addRandomTrade">
              <el-icon>
                <Plus />
              </el-icon>
              添加交易
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="chart-container">
        <TradingChart 
          :chart-data="tradingData" 
          height="450px"
        />
      </div>
      

    </el-card>
    
    <el-card class="chart-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>交易记录</span>
          <div class="stats">
            <el-tag type="success" size="small">买入: {{ buyCount }}笔</el-tag>
            <el-tag type="danger" size="small" style="margin-left: 10px">卖出: {{ sellCount }}笔</el-tag>
          </div>
        </div>
      </template>
      
      <el-table :data="tradingData" style="width: 100%" max-height="400">
        <el-table-column prop="Date" label="交易日期" width="120" sortable>
          <template #default="scope">
            <span>{{ formatDate(scope.row.Date) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Price" label="交易价格" width="120" sortable>
          <template #default="scope">
            <span>{{ scope.row.Price.toFixed(2) }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="BuyVol" label="买入量" width="120" sortable>
          <template #default="scope">
            <span v-if="scope.row.BuyVol > 0" class="amount-buy">
              {{ scope.row.BuyVol.toLocaleString() }}股
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="SellVol" label="卖出量" width="120" sortable>
          <template #default="scope">
            <span v-if="scope.row.SellVol > 0" class="amount-sell">
              {{ scope.row.SellVol.toLocaleString() }}股
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="交易金额" width="150">
          <template #default="scope">
            <div>
              <div v-if="scope.row.BuyVol > 0" class="amount-buy">
                买入: {{ (scope.row.Price * scope.row.BuyVol).toLocaleString() }}元
              </div>
              <div v-if="scope.row.SellVol > 0" class="amount-sell">
                卖出: {{ (scope.row.Price * scope.row.SellVol).toLocaleString() }}元
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeTrade(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div style="margin-top: 20px">
        <el-divider>添加交易记录</el-divider>
        <el-form :model="newTrade" inline>
          <el-form-item label="日期">
            <el-date-picker 
              v-model="newTrade.Date" 
              type="date" 
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="价格">
            <el-input-number v-model="newTrade.Price" :precision="2" :step="0.01" :min="0" placeholder="交易价格" />
          </el-form-item>
          <el-form-item label="买入量">
            <el-input-number v-model="newTrade.BuyVol" :step="100" :min="0" placeholder="买入数量" />
          </el-form-item>
          <el-form-item label="卖出量">
            <el-input-number v-model="newTrade.SellVol" :step="100" :min="0" placeholder="卖出数量" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addTrade">添加交易</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import TradingChart from '@/components/chart/TradingChart.vue'

// 移除了图表配置对象

// 生成随机交易数据
const generateRandomTradingData = (days = 30) => {
  const data = []
  const today = new Date()
  let currentPrice = 100 + Math.random() * 50 // 基础价格在100-150之间
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)
    
    // 随机决定是否有交易（70%概率有交易）
    if (Math.random() > 0.3) {
      // 价格波动
      const priceChange = (Math.random() - 0.5) * currentPrice * 0.05
      currentPrice = Math.max(10, currentPrice + priceChange)
      
      // 随机生成买入和卖出量
      const buyVol = Math.random() > 0.5 ? Math.floor((Math.random() * 10 + 1) * 1000) : 0
      const sellVol = Math.random() > 0.5 ? Math.floor((Math.random() * 8 + 1) * 1000) : 0
      
      // 确保至少有一种交易
      if (buyVol === 0 && sellVol === 0) {
        if (Math.random() > 0.5) {
          data.push({
            Date: date.toISOString().split('T')[0],
            BuyVol: Math.floor((Math.random() * 10 + 1) * 1000),
            SellVol: 0,
            Price: parseFloat(currentPrice.toFixed(2))
          })
        } else {
          data.push({
            Date: date.toISOString().split('T')[0],
            BuyVol: 0,
            SellVol: Math.floor((Math.random() * 8 + 1) * 1000),
            Price: parseFloat(currentPrice.toFixed(2))
          })
        }
      } else {
        data.push({
          Date: date.toISOString().split('T')[0],
          BuyVol: buyVol,
          SellVol: sellVol,
          Price: parseFloat(currentPrice.toFixed(2))
        })
      }
    }
  }
  
  return data
}

// 交易数据
const tradingData = ref(generateRandomTradingData())

// 统计数据
const buyCount = computed(() => {
  return tradingData.value.filter(item => item.BuyVol > 0).length
})

const sellCount = computed(() => {
  return tradingData.value.filter(item => item.SellVol > 0).length
})

// 刷新数据
const refreshData = () => {
  tradingData.value = generateRandomTradingData()
  ElMessage.success('数据已刷新')
}

// 添加随机交易
const addRandomTrade = () => {
  const today = new Date()
  const randomDays = Math.floor(Math.random() * 30)
  const date = new Date(today)
  date.setDate(today.getDate() - randomDays)
  
  const buyVol = Math.random() > 0.5 ? Math.floor((Math.random() * 10 + 1) * 1000) : 0
  const sellVol = Math.random() > 0.5 ? Math.floor((Math.random() * 8 + 1) * 1000) : 0
  
  // 确保至少有一种交易
  const newTradeData = {
    Date: date.toISOString().split('T')[0],
    BuyVol: buyVol === 0 && sellVol === 0 ? Math.floor((Math.random() * 10 + 1) * 1000) : buyVol,
    SellVol: sellVol,
    Price: parseFloat((Math.random() * 100 + 50).toFixed(2))
  }
  
  tradingData.value.push(newTradeData)
  tradingData.value.sort((a, b) => new Date(a.Date) - new Date(b.Date))
  
  ElMessage.success('随机交易已添加')
}

// 新交易记录
const newTrade = ref({
  Date: '',
  Price: 0,
  BuyVol: 0,
  SellVol: 0
})

// 添加交易记录
const addTrade = () => {
  if (!newTrade.value.Date) {
    ElMessage.warning('请选择交易日期')
    return
  }
  
  if (newTrade.value.Price <= 0) {
    ElMessage.warning('交易价格必须大于0')
    return
  }
  
  if (newTrade.value.BuyVol <= 0 && newTrade.value.SellVol <= 0) {
    ElMessage.warning('买入量或卖出量至少有一个大于0')
    return
  }
  
  // 添加新交易记录
  tradingData.value.push({
    Date: newTrade.value.Date,
    BuyVol: newTrade.value.BuyVol || 0,
    SellVol: newTrade.value.SellVol || 0,
    Price: newTrade.value.Price
  })
  
  // 按日期排序
  tradingData.value.sort((a, b) => new Date(a.Date) - new Date(b.Date))
  
  // 重置表单
  newTrade.value.Date = ''
  newTrade.value.BuyVol = 0
  newTrade.value.SellVol = 0
  newTrade.value.Price = 0
  
  ElMessage.success('交易记录已添加')
}

// 删除交易记录
const removeTrade = (index) => {
  tradingData.value.splice(index, 1)
  ElMessage.success('交易记录已删除')
}

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr.substring(5) // 显示 MM-DD
}
</script>

<style scoped>
.trading-chart-demo {
  padding: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats {
  display: flex;
  align-items: center;
}

.chart-container {
  margin-top: 10px;
  margin-bottom: 20px;
}

.chart-controls {
  margin-top: 20px;
}

.el-divider {
  margin: 16px 0;
}

.el-form-item {
  margin-bottom: 10px;
}

.amount-buy {
  color: #67C23A;
  font-weight: bold;
}

.amount-sell {
  color: #F56C6C;
  font-weight: bold;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
}
</style>